#
# "@(#) $Id: LAlbumView.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
from kdeemul import *
from Library import *
from LTrackDrag import *
from LSettings import *
from utils import *

#
# a list view item showing an individual album name
# sort key used to distinguish from "all items" value
#
class LAlbumViewItem(KListViewItem):
	def __init__(self,container,album):
		KListViewItem.__init__(self,container,album)
		self.sortKey = QString("ZA %s" % album.lower())
		self.setDragEnabled(True)

	def key(self,column,ascending):
		return self.sortKey

	def album(self):
		return unikode(self.text(0))

#
# a list view item representing all albums
# special trick to force it to the top of the list no matter the sort direction
#
class LAllAlbumsViewItem(LAlbumViewItem):
	def __init__(self,container,count):
		LAlbumViewItem.__init__(self,container,unikode(i18n("All (%d Albums)")) % (count))
		self.akey = QString('AA')
		self.dkey = QString('ZZ')
		self.setDragEnabled(False)
		
	def key(self,column,ascending):
		if ascending:
			return self.akey
		else:
			return self.dkey

	def setCount(self,count):
		self.setText(0,unikode(i18n("All (%d Albums)")) % (count))

	def album(self):
		return None

class LAlbumView(KListView):
	def __init__(self, container):
		KListView.__init__(self,container,"albums")
		self.settings = LSettings.settings()
		self.bulkEdit = False
		self.setSelectionMode(QListView.Extended)
		self.setAlternateBackground(QColor())
		self.library = Library.mainLibrary()
		self.allItem = None
		self.playlist = self.library.playlistWithName("Library")
		if self.playlist==None:
			print "Error: LAlbumView has no playlist"
		self.loadHeaders()
		#self.loadAlbumsForArtists()
		self.currentArtists = None
		self.connect(self,SIGNAL("selectionChanged()"),self.selectAlbumItems)
		self.playlist.connect(PYSIGNAL("addedTrack"),self.addedTrack)
		self.playlist.connect(PYSIGNAL("removedTrack"),self.refresh)
		self.library.connect(PYSIGNAL("changedTrackArtistOrAlbum"),self.refresh)
		self.library.connect(PYSIGNAL("bulkEditBegin"),self.bulkEditBegin)
		self.library.connect(PYSIGNAL("bulkEditEnd"),self.bulkEditEnd)
		
	def bulkEditBegin(self):
		self.bulkEdit = True
	
	def bulkEditEnd(self):
		self.bulkEdit = False
		self.refresh()

	def selectAlbumItems(self):
		if self.allItem.isSelected():
			item = self.firstChild()
			while item:
				if item!=self.allItem and item.isSelected():
					item.setSelected(False)
				item = item.itemBelow()
			self.selectAlbums(None)
		else:
			albums = []
			item = self.firstChild()
			while item:
				if item.isSelected():
					albums.append(item.album())
				item = item.itemBelow()
			self.selectAlbums(albums)

	def selectAlbums(self,albums):
		if albums==None:
			self.settings['Main Library Albums'] = []
		else:
			self.settings['Main Library Albums'] = albums
		self.emit(PYSIGNAL("selectAlbums"),(self.currentArtists,albums))

	def loadHeaders(self):
		self.addColumn(i18n("Album"))
		self.setFullWidth(True)
		self.setShowSortIndicator(True)
		self.setSorting(0,self.settings.get('Main Library Albums Sort Ascending',True))

	def loadAlbumsForArtists(self,artists=None):
		#print "LAlbumView reloading",self.bulkEdit
		if not self.bulkEdit:
			self.clear()
			if self.playlist:
				self.currentArtists = artists
				albums = {}
				tracks = self.playlist.tracks
				for track in tracks:
					if track:
						artist = None
						if track.artist!=None: artist = unikode(track.artist)
						if artists==None or len(artists)==0 or artist in artists:
							album = None
							if track.album!=None: album = unikode(track.album)
							if album!=None and len(album)>0:
								albums[album.upper()] = album
				albums = albums.values()
				#albums.sort()
				sortingDirection = self.settings.get('Main Library Albums Sort Ascending',True)
				self.setUpdatesEnabled(False)
				self.blockSignals(True)
				self.setSorting(-1,True)
				self.allItem = LAllAlbumsViewItem(self,len(albums))
				for album in albums:
					item = LAlbumViewItem(self,album)
				self.setSorting(0,sortingDirection)
				self.blockSignals(False)
				self.setUpdatesEnabled(True)
				self.update()
				self.loadFromPrefs()
			else:
				print "Album playlist is None"

	def refresh(self):
		if not self.bulkEdit:
			self.loadAlbumsForArtists(self.currentArtists)
	
	#
	# optimize the common case of new track
	#
	def addedTrack(self,playlist,trackID):
		if not self.bulkEdit:
			track = self.playlist.trackWithTrackID(trackID)
			if track:
				artists = self.currentArtists
				artist = unikode(track.artist)
				album = unikode(track.album)
				if album and len(album)>0:
					if artists==None or len(artists)==0 or artist in artists:
						item = self.firstChild()
						count = 0
						while item:
							count = count+1
							if unikode(item.album())==album:
								return
							item = item.itemBelow()
						item = LAlbumViewItem(self,album)
						self.allItem.setCount(count)
					
	def selectedAlbums(self):
		albums = []
		item = self.firstChild()
		while item:
			if item.isSelected():
				albums.append(item.album())
			item = item.itemBelow()
		return albums

	def loadFromPrefs(self):
		#print "loading albums from prefs"
		albums = self.settings.get('Main Library Albums',[])
		found = False
		for album in albums:
			found = found or self.selectItemForAlbum(album)
		if not found:
			albums = []
			self.allItem.setSelected(True)
		self.selectAlbums(albums)
	
	def selectItemForAlbum(self,album):
		item = self.firstChild()
		while item:
			if item.album()==album:
				item.setSelected(True)
				return True
			item = item.itemBelow()
		return False
	
	def dragObject(self):
		artists = self.currentArtists
		albums = self.selectedAlbums()
		print "dragging",artists,':',albums
		trackIDs = self.playlist.trackIDsForArtistsAndAlbums(artists,albums)
		#print "dragging",trackIDs
		drag = LTrackDrag(trackIDs,self.playlist,self)
		drag.dragCopy()

	def setSorting(self,column,ascending):
		KListView.setSorting(self,column,ascending)
		self.settings['Main Library Albums Sort Ascending'] = not not ascending
